package com.sunop.panticommon.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.client.support.BasicAuthenticationInterceptor;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;

@Configuration
public class ElasticRestTemplateConfig {

    @Value("${spring.elasticsearch.username:#{null}}")  // 安全写法
    private String username;

    @Value("${spring.elasticsearch.password:#{null}}")
    private String password;

    @Bean(name = "elasticsearchRestTemplate")
    public RestTemplate elasticsearchRestTemplate() {
        RestTemplate restTemplate = new RestTemplate();

        // 添加认证拦截器（当配置存在时）
        if (username != null && password != null) {
            restTemplate.setInterceptors(Collections.singletonList(
                    new BasicAuthenticationInterceptor(username, password)
            ));
        }

        // 超时设置
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(5000);
        factory.setReadTimeout(10000);
        restTemplate.setRequestFactory(factory);

        return restTemplate;
    }
}